package com.hua.store.web.servlet;

import com.hua.store.domin.Cart;
import com.hua.store.domin.CartItem;
import com.hua.store.domin.Product;
import com.hua.store.domin.User;
import com.hua.store.service.ProductService;
import com.hua.store.service.impl.ProductServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "CarServlet", urlPatterns = "/CarServlet")
public class CarServlet extends BaseServlet {

    public String addToCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("utf-8");

        //判断用户是否登录，如果未登录，则不能添加至购物车
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            req.setAttribute("msg", "请登录后再购买商品");
            return "/jsp/login.jsp";
        }


        //从session获取购物车
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //如果获取不到,创建购物车对象,放在session中

        if (cart == null) {
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        //如果获取到,使用即可
        //获取到商品id,数量
        String pid = req.getParameter("pid");
        int num = Integer.parseInt(req.getParameter("num"));
        //通过商品id查询都商品对象
        ProductService service = new ProductServiceImpl();
        Product product = service.findProductByPid(pid);
        //获取到待购买的购物项
        CartItem cartItem = new CartItem();
        cartItem.setNum(num);
        cartItem.setProduct(product);

        //调用购物车上的方法
        cart.addToCart(cartItem);
        //重定向到/jsp/cart.jsp
        resp.sendRedirect("/jsp/cart.jsp");
        return null;
    }

    //removeCartItem
    public String removeCartItem(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String pid = req.getParameter("pid");
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        cart.removeCartItem(pid);
        resp.sendRedirect("/jsp/cart.jsp");
        return null;
    }

    //clearCart
    public String clearCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        cart.clearCart();
        resp.sendRedirect("/jsp/cart.jsp");
        return null;
    }
}
